import requests
import re
from hashlib import md5

# 在这里填入你在百度翻译开放平台申请到的APP ID和密钥
APP_ID = "20201112000614722"
SECRET_KEY = "LiinO0W7NmmF6RHldPWX"

html_file_path = "selectpage.html"

def baidu_translate(word):
    salt = "1435660288"
    sign = md5((APP_ID + word + salt + SECRET_KEY).encode()).hexdigest()

    url = "https://fanyi-api.baidu.com/api/trans/vip/translate"
    params = {
        "q": word,
        "from": "zh",
        "to": "en",
        "appid": APP_ID,
        "salt": salt,
        "sign": sign
    }

    response = requests.get(url, params=params)
    result = response.json()

    if "trans_result" in result:
        return result["trans_result"][0]["dst"]
    return None

with open(html_file_path, 'r', encoding='utf-8') as file:
    html_code = file.read()

chinese_words = re.findall('[\u4e00-\u9fa5]+', html_code)
translation_dict = {}

for word in chinese_words:
    translation = baidu_translate(word)
    translated_word = f"{{:__('{translation}')}}"
    html_code = html_code.replace(word, translated_word)
    translation_dict[word] = translation

translated_html_file_path = "translated_html_file_path.html"
with open(translated_html_file_path, 'w', encoding='utf-8') as file:
    file.write(html_code)

print("翻译后的HTML代码已写入：", translated_html_file_path)
print(translation_dict)